import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:manual/components/toast_overlay.dart';
import 'package:manual/utils/logger.dart';
import 'package:manual/utils/method_channels.dart';
import 'dart:io';
import 'package:manual/utils/premission.dart';
import 'package:permission_handler/permission_handler.dart';



class CameraGalleryPage extends StatefulWidget {
  const CameraGalleryPage({super.key});

  @override
  _CameraGalleryPageState createState() => _CameraGalleryPageState();
}

class _CameraGalleryPageState extends State<CameraGalleryPage> {
  final ImagePicker _picker = ImagePicker();
  File? _selectedImage;

  // 打开相册
  Future<void> _pickImageFromGallery() async {
    // 检查权限
    bool granted = await PermissionManager.requestGalleryPermissions();

    if (!granted) {
      PermissionManager.openSettings(context, const Text('需要相册访问权限，建议前往设置开通权限。'));
      return;
    }

    // 权限通过后打开相册
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _selectedImage = File(image.path);
      });
    }
  }

  // 打开摄像头
  Future<void> _pickImageFromCamera() async {
    // 检查权限
    bool granted = await PermissionManager.requestPermissions(
      [Permission.camera],
    );
    Logger.info("granted $granted" , tag:"PERMISSION");
    if (!granted) {
      PermissionManager.openSettings(context, const Text('当前无摄像头权限，建议前往设置开通权限。'));
      return;
    }

    // 权限通过后打开摄像头
    final XFile? image = await _picker.pickImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        _selectedImage = File(image.path);
      });
    }
  }



  Future <void> saveGallery(String type)  async {
    final res = await MethodChannels.saveToGallery(type);
    if(res){
      Toast.show(context, "保存成功");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Camera and Gallery Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _selectedImage != null
                ? Image.file(_selectedImage!) // 显示选中的图片
                : const Text('没有选中图片'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImageFromGallery,
              child: const Text('从相册选择图片'),
            ),
            ElevatedButton(
              onPressed: _pickImageFromCamera,
              child: const Text('拍摄照片'),
            ),
            ElevatedButton(
              onPressed:() => saveGallery("local"),
              child: const Text('保存本地图片到相册'),
            ),
            ElevatedButton(
              onPressed:() => saveGallery("mesh"),
              child: const Text('保存网络图片到相册'),
            ),
          ],
        ),
      ),
    );
  }
}
